<template>
  <div class="page-common-layout custom-tablePage-container">
    <div class="screen-conditions-container">
      <ScreenConditions :isDataType="false">
        <template slot="conditions">
          <a-input
            style="width: 380px;"
            v-model="condition.schemeName"
            placeholder="请输入方案名称"
          ></a-input>
          <a-select
            class="project-select"
            showSearch
            allowClear
            placeholder="请选择方案类型"
            :filter-option="filterOption"
            v-model="condition.schemeType"
            @change="search()"
          >
            <a-select-option
              :value="item.dicItemCode"
              v-for="item in schemeTypeSoucre"
              :key="item.uuid"
            >
              {{ item.dicItemName }}
            </a-select-option>
          </a-select>
          <a-select
            class="project-select"
            showSearch
            allowClear
            placeholder="请选择编制单位"
            :filter-option="filterOption"
            v-model="condition.preparedUnit"
            @change="search()"
          >
            <a-select-option
              :value="item.orgCode"
              v-for="item in blockSoucre"
              :key="item.uuid"
            >
              {{ item.orgName }}
            </a-select-option>
          </a-select>
          <!--  -->
          <a-input
            style="width: 380px;"
            v-model="condition.preparedUser"
            placeholder="请输入编制人"
          ></a-input>
          <!--  -->
          <a-range-picker
            :placeholder="['开始日期', '结束日期']"
            format="YYYY-MM-DD HH:mm"
            valueFormat="YYYY-MM-DD HH:mm"
            v-model="condition.date"
            :show-time="{
              hideDisabledOptions: true,
              defaultValue: [
                moment('00:00:00', 'HH:mm'),
                moment('11:59:59', 'HH:mm'),
              ],
            }"
          />
        </template>
        <template slot="operate">
          <a-button class="cu-btn-primary" icon="search" @click="search()">
            查询
          </a-button>
          <a-button class="cu-btn-filter" icon="reload" @click="reset()">
            重置
          </a-button>
        </template>
      </ScreenConditions>
    </div>
    <div class="table-body-container">
      <div class="table-operate">
        <a-button
          class="cu-btn-primary margin-bottom-xs"
          icon="plus"
          @click="handleAddModal({}, 1)"
          v-action:sgfash_add
        >
          新增
        </a-button>
      </div>
      <div class="table-main">
        <vxe-table
          ref="xTable"
          height="99%"
          align="left"
          show-overflow
          show-header-overflow
          border="inner"
          :data="tableData"
          :column-config="{ resizable: true }"
          size="small"
          :loading="loading"
          :row-config="{ keyField: 'uuid' }"
          :expand-config="{
            reserve: true,
            visibleMethod: visibleMethod,
          }"
        >
          <vxe-column type="expand" width="26">
            <template #content="{ row }">
              <div class="expand-wrapper">
                <vxe-table
                  align="center"
                  border="inner"
                  :data="row.historys || []"
                  :column-config="{ resizable: true }"
                  show-overflow
                  show-header-overflow
                  size="small"
                >
                  <vxe-column field="versionNumber" title="版本号">
                  </vxe-column>
                  <vxe-column field="schemeName" title="方案名称"> </vxe-column>
                  <vxe-column field="schemeTypeDesc" title="方案类型">
                  </vxe-column>
                  <vxe-column title="方案">
                    <template #default="{ row }">
                      <div class="files-icon">
                        <!-- 预览 -->
                        <a-tooltip placement="top">
                          <template slot="title">
                            预览
                          </template>
                          <a-icon
                            type="eye"
                            @click="handelFileModal(row.files, '方案')"
                          />
                        </a-tooltip>
                        <!-- 下载 -->
                        <a-tooltip placement="top" v-action:sgfash_ download>
                          <template slot="title">
                            下载
                          </template>
                          <a-icon
                            type="download"
                            @click="downloadFile(row.files, '方案')"
                          />
                        </a-tooltip>
                      </div>
                    </template>
                  </vxe-column>
                  <vxe-column field="preparedUser" title="编制人"> </vxe-column>
                  <vxe-column field="preparedUnit" title="编制单位">
                  </vxe-column>
                  <vxe-column field="preparedTime" title="编制时间">
                  </vxe-column>
                  <vxe-column field="reason" title="驳回原因"> </vxe-column>
                  <vxe-column
                    field="operate"
                    width="60"
                    title="操作"
                    fixed="right"
                  >
                    <template #default="{ row }">
                      <div class="text-button-group">
                        <a-tooltip placement="top">
                          <template slot="title">
                            查看
                          </template>
                          <a-icon
                            type="file-search"
                            @click="handleAddModal(row, 3)"
                          />
                        </a-tooltip>
                      </div>
                    </template>
                  </vxe-column>
                </vxe-table>
              </div>
            </template>
          </vxe-column>
          <vxe-column
            type="seq"
            width="50"
            title="序号"
            align="center"
          ></vxe-column>
          <vxe-column field="schemeName" title="方案名称"> </vxe-column>
          <vxe-column field="schemeTypeDesc" title="方案类型"> </vxe-column>
          <vxe-column title="方案">
            <template #default="{ row }">
              <div class="files-icon">
                <!-- 预览 -->
                <a-tooltip placement="top">
                  <template slot="title">
                    预览
                  </template>
                  <a-icon
                    type="eye"
                    @click="handelFileModal(row.files, '方案')"
                  />
                </a-tooltip>
                <!-- 下载 -->
                <a-tooltip placement="top" v-action:sgfash_ download>
                  <template slot="title">
                    下载
                  </template>
                  <a-icon
                    type="download"
                    @click="downloadFile(row.files, '方案')"
                  />
                </a-tooltip>
              </div>
            </template>
          </vxe-column>
          <vxe-column field="preparedUser" title="编制人"> </vxe-column>
          <vxe-column field="preparedUnit" title="编制单位"> </vxe-column>
          <vxe-column field="preparedTime" title="编制时间"> </vxe-column>
          <vxe-column title="状态" width="100">
            <template #default="{ row }">
              <div class="state" :class="[filterStateClass(row.approveStatus)]">
                {{ filterStateName(row.approveStatus) }}
              </div>
            </template>
          </vxe-column>
          <vxe-column field="operate" width="180" title="操作" fixed="right">
            <template #default="{ row }">
              <div class="text-button-group">
                <!-- 详情 -->
                <a-tooltip placement="top">
                  <template slot="title">
                    查看
                  </template>
                  <a-icon type="file-search" @click="handleAddModal(row, 3)" />
                </a-tooltip>
                <!-- 提交 -->
                <a-tooltip
                  placement="top"
                  v-if="row.submit"
                  v-action:sgfash_submit
                >
                  <template slot="title">
                    提交
                  </template>
                  <icon-fonts
                    icon="icon-fabu-tijiao-tijiaobanben"
                    class="submit"
                    @change="handleSubmit(row)"
                  ></icon-fonts>
                </a-tooltip>
                <a-tooltip placement="top" v-if="row.approveRecord">
                  <template slot="title">
                    审批记录
                  </template>
                  <icon-fonts
                    icon="icon-shenpi"
                    class="record"
                    @change="gotoApprovalRecord(row)"
                  ></icon-fonts>
                </a-tooltip>
                <!-- 审批 -->
                <a-tooltip placement="top" v-if="row.approve">
                  <template slot="title">
                    审批
                  </template>
                  <icon-fonts
                    icon="icon-shenpi1"
                    class="approve"
                    @change="handleAddModal(row, 4)"
                  ></icon-fonts>
                </a-tooltip>
                <!-- 编辑 -->
                <a-tooltip v-if="row.edit" v-action:sgfash_edit>
                  <template slot="title">
                    编辑
                  </template>
                  <a-icon type="edit" @click="handleAddModal(row, 2)" />
                </a-tooltip>
                <!-- 删除 -->
                <a-tooltip v-if="row.del" v-action:sgfash_delete>
                  <template slot="title">
                    删除
                  </template>
                  <a-icon type="delete" @click="handleDelClick(row)" />
                </a-tooltip>
              </div>
            </template>
          </vxe-column>
        </vxe-table>
      </div>
      <div class="table-pager">
        <vxe-pager
          size="small"
          background
          :current-page.sync="pager.page"
          :page-size.sync="pager.pageSize"
          :total="pager.total"
          :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'Sizes']"
          :page-sizes="[20, 50, 100, 500]"
          @page-change="paginationChange"
        >
          <template #left>
            <div class="vxe-pager-left-tip-container">
              共<span>{{ pager.total }}</span
              >条
            </div>
          </template>
        </vxe-pager>
      </div>
    </div>
    <!-- 处理 -->
    <addModal
      :visible.sync="addModal.visible"
      :parameter="addModal.soucre"
      :operateType="addModal.operateType"
    ></addModal>
    <!-- 审批记录 -->
    <comment-modal ref="commentModal"></comment-modal>
    <!-- 查看附件 -->
    <viewFileModal
      :visible.sync="viewFileModal.visible"
      :fileList="viewFileModal.fileList"
      :subtitle="viewFileModal.name"
    ></viewFileModal>
    <!-- 附件预览 -->
    <previewModal
      ref="previewModal"
      :visible.sync="previewModal.visible"
      :loading="previewModal.loading"
    ></previewModal>
  </div>
</template>

<script>
//施工方案审核
import moment from "moment";
import { mapGetters } from "vuex";
import { getToken, downloadDfs } from "@/utils/TopVUI";
import ScreenConditions from "@/components/extendCustom/ScreenConditions";
import addModal from "./components/addModal.vue";
//审批记录
import commentModal from "@/pages/workflow/oaLeave/comment.vue";
//文件列表
import viewFileModal from "@/components/extendCustom/view-file-modal";
//单文件预览
import previewModal from "@/pages/document/minio/previewModal";
import { getDicItemByCode, getAllQxSecs } from "@/api/common.js";
import {
  pageProgrammeExamine,
  deleteProgrammeExamine,
  submitProgrammeExamine,
} from "@/api/engineering";
import { start } from "nprogress";
export default {
  components: {
    ScreenConditions,
    addModal,
    commentModal,
    viewFileModal,
    previewModal,
  },
  data() {
    return {
      //项目
      projectLoading: false,
      projectSoucre: [],
      //查询条件
      condition: {
        //方案名称
        schemeName: "",
        //方案类型
        schemeType: undefined,
        //编制人
        preparedUser: "",
        //编制单位
        preparedUnit: undefined,
        //编制时间
        date: [],
      },
      //列表
      loading: false,
      tableData: [],
      pager: {
        page: 1,
        pageSize: 50,
        total: 0,
      },
      //新增
      addModal: {
        visible: false,
        soucre: {},
        operateType: 1,
      },
      //查看附件
      viewFileModal: {
        name: "",
        visible: false,
        fileList: [],
      },
      //单文件预览
      previewModal: {
        visible: false,
        loading: false,
      },
      //方案类型
      schemeTypeSoucre: [],
      //编制单位
      blockSoucre: [],
    };
  },
  computed: {
    ...mapGetters(["configData", "userInfo"]),
    kkFileView() {
      let index = this.configData.findIndex(
        (item) => item.code === "kkFileView"
      );
      if (index >= 0) {
        return this.configData[index].value;
      } else {
        return "http://192.168.1.216:8012/onlinePreview";
      }
    },
  },
  mounted() {
    this.getData();
  },
  methods: {
    moment,
    //查询数据
    async getData() {
      //方案类型
      this.schemeTypeSoucre = await this.getDicCodeData("schemeType");
      //编制单位
      await this.getOrgData();
      //列表
      this.getTableData();
    },

    //查询字典表
    getDicCodeData(dicCode = "") {
      return new Promise((resolve, reject) => {
        getDicItemByCode({ code: dicCode })
          .then((res) => {
            let { data } = res;
            resolve(data);
          })
          .catch((_) => {
            reject();
          })
          .finally((_) => {});
      });
    },

    //查询编制单位
    getOrgData() {
      return new Promise((resolve, reject) => {
        getAllQxSecs({ tenantCode: "", type: 1 })
          .then((res) => {
            this.blockSoucre = res?.data ?? [];
            resolve();
          })
          .catch((_) => {
            this.blockSoucre = [];
            reject();
          })
          .finally((_) => {});
      });
    },

    analysisPath(files = "[]") {
      let list = JSON.parse(files ?? "[]");
      return list;
    },

    //预览
    handelFileModal(files = "[]", name) {
      const filesList = this.analysisPath(files);
      let { url } = filesList?.[0] ?? {};
      if (filesList.length == 0) {
        return;
      }
      if (filesList.length == 1) {
        this.defaultViewFile(url);
      } else {
        this.viewFileModal.name = name;
        this.viewFileModal.fileList = filesList;
        this.viewFileModal.visible = true;
      }
    },
    //普通文件预览
    defaultViewFile(url) {
      this.previewModal.loading = true;
      this.$refs.previewModal.type = "file";
      this.$refs.previewModal.fileUrl =
        this.kkFileView +
        "/onlinePreview?url=" +
        encodeURIComponent(Base64.encode(url)) +
        "&watermarkTxt=" +
        //水印内容
        encodeURIComponent("") +
        "&token=" +
        getToken();
      this.previewModal.visible = true;
      this.previewModal.loading = false;
    },
    downloadFile(files = "[]", name) {
      const filesList = this.analysisPath(files);
      let { url } = filesList?.[0] ?? {};
      if (filesList.length == 0) {
        return;
      }
      if (filesList.length == 1) {
        downloadDfs(url);
      } else {
        this.viewFileModal.name = name;
        this.viewFileModal.fileList = filesList;
        this.viewFileModal.visible = true;
      }
    },

    handleAddModal(row, type) {
      this.addModal.operateType = type;
      this.addModal.soucre = row;
      this.addModal.visible = true;
    },

    //审批记录
    gotoApprovalRecord(record) {
      this.$refs.commentModal.getCommentList(record.uuid);
    },

    //删除
    handleDelClick(row) {
      let dataLength = this.tableData.length;
      let that = this;
      that.$confirm({
        title: "提示",
        content: "确定删除该数据吗？删除之后不可恢复！",
        okText: "确定",
        cancelText: "取消",
        icon: () =>
          that.$createElement("a-icon", {
            props: {
              key: "warning",
              type: "exclamation-circle",
              twoToneColor: "#faad14",
            },
          }),
        onOk() {
          deleteProgrammeExamine({ uuid: row.uuid })
            .then((res) => {
              if (res.statusCode === 200 || res === 1) {
                that.$message.success("删除成功", 1.5);
                if (dataLength == 1 && that.pager.page > 1) {
                  that.pager.page -= 1;
                }
                that.getTableData();
              } else {
                that.$message.error(res.message);
              }
            })
            .catch((_) => {});
        },
      });
    },

    //提交
    handleSubmit(row) {
      let that = this;
      let { uuid } = row;
      const h = this.$createElement;
      this.$confirm({
        title: "您确定提交所选内容?",
        content: "",
        okText: "确定",
        okType: "primary",
        cancelText: "取消",
        centered: true,
        icon: () =>
          h("a-icon", {
            props: {
              type: "question-circle",
              theme: "filled",
            },
            style: "color:#FAAD14",
          }),
        onOk() {
          that.loading = true;
          submitProgrammeExamine({ uuid })
            .then((res) => {
              if (res.statusCode === 200 || res === 1) {
                that.$message.success("提交成功", 1.5);
                that.getTableData();
              } else {
                that.$message.error(res?.message ?? "提交失败");
              }
            })
            .catch((_) => {
              that.$message.error(res?.message ?? "提交失败");
            })
            .finally(() => {
              that.loading = false;
            });
        },
        onCancel() {},
      });
    },

    //查询
    search() {
      this.pager.page = 1;
      this.getTableData();
    },

    //重置
    reset() {
      //查询条件
      this.condition = {
        //方案名称
        schemeName: "",
        //方案类型
        schemeType: undefined,
        //编制人
        preparedUser: "",
        //编制单位
        preparedUnit: undefined,
        //编制时间
        date: [],
      };
      this.search();
    },

    visibleMethod({ row }) {
      if (row.historys && row.historys.length != 0) {
        return true;
      } else {
        return false;
      }
    },

    //查询列表数据
    getTableData() {
      this.loading = true;
      let { page, pageSize } = this.pager;
      //查询条件
      let {
        schemeName,
        schemeType = "",
        preparedUser,
        preparedUnit = "",
        date,
      } = this.condition;
      return new Promise((resolve, reject) => {
        pageProgrammeExamine({
          page,
          pageSize,
          schemeName,
          schemeType,
          preparedUser,
          preparedUnit,
          startTime: date?.[0] ?? "",
          endTime: date?.[1] ?? "",
        })
          .then((res) => {
            this.tableData = res?.data?.rows || [];
            this.pager.total = res?.data?.totalCount || 0;
            resolve();
          })
          .catch((_) => {
            this.tableData = [];
            this.pager.total = 0;
            reject();
          })
          .finally((_) => {
            this.loading = false;
          });
      });
    },

    //监听分页切换
    paginationChange({ currentPage, pageSize }) {
      this.pager.page = currentPage;
      this.pager.pageSize = pageSize;
      this.getTableData();
    },

    filterStateName(val) {
      switch (val) {
        case 0:
          return "待提交";
        case 1:
          return "审批中";
        case 2:
          return "审批通过";
        case 3:
          return "驳回";
        default:
          return "-";
      }
    },

    filterStateClass(val) {
      switch (val) {
        case 0:
          return "default";
        case 1:
          return "ing";
        case 2:
          return "lock";
        case 3:
          return "error";
        default:
          return "";
      }
    },

    //select 搜索过滤
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text
          .toLowerCase()
          .indexOf(input.toLowerCase()) >= 0
      );
    },
  },
};
</script>

<style lang="scss" scoped>
.expand-wrapper {
  padding: 10px;
  box-sizing: border-box;
}

.state {
  &::before {
    position: relative;
    display: inline-block;
    content: "";
    width: 8px;
    height: 8px;
    background: #239b53;
    border-radius: 0px 0px 0px 0px;
    border-radius: 50%;
    margin-right: 10px;
  }
  &.default {
    &::before {
      background: #8c8c8c;
    }
  }
  &.ing {
    &::before {
      background: #f07f17;
    }
  }
  &.lock {
    &::before {
      background: #239b53;
    }
  }

  &.error {
    &::before {
      background: #ff3f4a;
    }
  }
}
</style>
